<?php

namespace App\Http\Controllers\Back;

use App\Domain\Item\Service\ItemService;
use App\Model\Book;
use App\Model\SceneryRegion;
use App\Model\SceneryType;
use App\Model\Picture;
use App\Util\Result;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

class BookController extends Controller
{

    private function leftBar()
    {
        return [
            'title' => '图书管理',
            'list' => [
                [
                    'title' => '书籍仓库',
                    'type' => 'book_list',
                    'url' => url('back/book'),
                ],
//                [
//                    'title' => '图书类型',
//                    'type' => 'book_type',
//                    'url' => url('back/book/bookType'),
//                ],
                [
                    'title' => '待上架书籍',
                    'type' => 'collect',
                    'url' => url('back/book/collect'),
                ],
                [
                    'title' => '在架书籍',
                    'type' => 'sjBook',
                    'url' => url('back/sjBook/index'),
                ],
                [
                    'title' => '外借图书',
                    'type' => 'ltBook',
                    'url' => url('back/ltBook/index'),
                ],
                [
                    'title' => '下架书籍',
                    'type' => 'xjBook',
                    'url' => url('back/xjBook/index'),
                ],
                [
                    'title' => '外售图书',
                    'type' => 'wsBook',
                    'url' => url('back/wsBook/index'),
                ],
                [
                    'title' => '异常图书',
                    'type' => 'ycBook',
                    'url' => url('back/ycBook/index'),
                ],
                [
                    'title' => '流通日志',
                    'type' => 'ltlog',
                    'url' => url('back/ltlog/index'),
                ],
            ]
        ];
    }

    protected $itemService = null;

    /**
     * @param Request $request
     * czs
     */
    public function __construct(Request $request,ItemService $itemService)
    {
        $this->request = $request;
        $this->limit = config('config.pageLimit');
        $leftBarArr = $this->leftBar();
        $this->itemService=$itemService;
        view()->share(['title' => $leftBarArr['title'], 'list' => $leftBarArr['list'], 'limit' => $this->limit]);
    }

    /**
     * 图书列表
     * czs
     */
    public function index()
    {
        $keyWord = $this->request->input('keyword');
        $res = Book::getLists($keyWord, $this->limit)->getData();
        $this->request->flash();
        return view('back/book/index')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('count2', $res['count2'])
            ->with('titleType', 'book_list');
    }

    public function edit($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $pic = DB::table('ttindex7')->where('ID', $id)->select('ImageUrl  as img')->first();
            if (empty($input['pic_url_only']) && empty($pic->img)) {
                return Result::failure()->setMsg("图片不能为空")->getResult();
            }
            //单图更新
            if ($pic->img != $input['pic_url_only']) {
                $input['ImageUrl'] = $input['pic_url_only'];
                unset($input['pic_url_only']);
            } else {
                unset($input['pic_url_only']);
            }

            $res = DB::table('ttindex7')->where('ID', $id)->update($input);
            if ($res) {
                return Result::success()->getResult();
            } else {
                return Result::failure()->getResult();
            }
        } else {
            $res = DB::table('ttindex7 as a')
                ->where('a.ID', $id)
                ->select('a.Title', 'a.ImageUrl')
                ->first();
            return view('back.book.edit')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'book_list');
        }
    }

    public function edit2($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $pic = DB::table('ttindex7')->where('ID', $id)->select('ImageUrl  as img')->first();
            if (empty($input['pic_url_only']) && empty($pic->img)) {
                return Result::failure()->setMsg("图片不能为空")->getResult();
            }
            //单图更新
            if ($pic->img != $input['pic_url_only']) {
                $input['ImageUrl'] = $input['pic_url_only'];
                unset($input['pic_url_only']);
            } else {
                unset($input['pic_url_only']);
            }
            $res = DB::table('ttindex7')->where('ID', $id)->update($input);
            if ($res) {
                return Result::success()->getResult();
            } else {
                return Result::failure()->getResult();
            }
        } else {
            $res = DB::table('ttindex7 as a')
                ->where('a.ID', $id)
                ->select('a.Title', 'a.ImageUrl')
                ->first();
            return view('back.book.edit2')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'collect');
        }
    }

    /**
     * 二级典藏
     */
    public function secCata($id)
    {
        $res = Book::getSecCata($id, $this->limit)->getData();
        return view('back/book/secCata')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('count2', $res['count2'])
            ->with('id', $id)->with('titleType', 'book_list');
    }

    public function editSecCata($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $pic = book::getPic($id)->getData();
            if (empty($input['pic_url_only']) && empty($pic->img)) {
                return Result::failure()->setMsg("图片不能为空")->getResult();
            }
            //单图更新
            if ($pic->img != $input['pic_url_only']) {
                $input['ImageUrl'] = $input['pic_url_only'];
                unset($input['pic_url_only']);
            } else {
                unset($input['pic_url_only']);
            }

            $res = book::updateData($input, $id);
            return $res->getResult();
        } else {
            $res = DB::table('circ_marc as a')
                ->where('a.MarcID', $id)
                ->select('a.Title', 'a.ImageUrl', 'a.Price', 'a.IID', 'a.Profile')
                ->first();
            return view('back.book.editSecCata')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'book_list');
        }
    }

    /**
     * 三级典藏
     */
    public function thirdCata($id)
    {
        $iid = DB::table('circ_marc as a')
            ->where('a.MarcID', $id)->value('a.IID');
        $res = Book::getThirdCata($id, $this->limit)->getData();
        return view('back/book/thirdCata')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('id', $id)->with('titleType', 'book_list')->with('iid', $iid);
    }

    public function editThirdCata($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $res = book::updateThirdCata($input, $id);
            $sel =$this->itemService->getItemById($id);
            if (!empty($sel->imageUrl) && !empty($sel->sold_price) && !empty($sel->rent_price) && !empty($sel->profile) && !empty($sel->title)  && !empty($sel->price)) {
                 $sel->update(['LTStatus' => 2]);
                return Result::success()->setMsg('更新成功并典藏')->getResult();
            }
            return $res->getResult();
        } else {
            $res = DB::table('Items as a')
                ->where('a.SerialNo', $id)
                ->select('a.sold_price', 'a.rent_price', 'a.MarcID')
                ->first();
            return view('back.book.editThirdCata')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'book_list');
        }
    }

    public function deleteThirdCata($id)
    {
        $sel = DB::table('Items')
            ->where('SerialNo', $id)
            ->where('LTStatus', 1);
        if (empty($sel->count())) {
            return Result::failure()->getResult();
        }
        $res = $sel->delete();
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function pldcCata()
    {
        $ids = $this->request->input('ids');
        $sel2 = DB::table('Items as a')
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->leftjoin('ttindex7 as c', 'c.ID', '=', 'b.IID')
            ->wherein('c.ID', $ids)
            ->select('a.SerialNo','b.ImageUrl', 'a.sold_price', 'a.rent_price', 'b.Profile','b.Price','b.Title')
            ->get();

        $res=false;

        foreach ($sel2 as $k => $v) {

            if (empty($v->ImageUrl) || empty($v->sold_price) || empty($v->rent_price) || empty($v->Profile) || empty($v->Price) || empty($v->Title)) {
                continue;
            }
            $res=DB::table('Items')->where('SerialNo',$v->SerialNo)->update(['LTStatus' => 2]);
        }
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function pldcSecCata()
    {
        $ids = $this->request->input('ids');
        $sel2 = DB::table('Items as a')
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->wherein('b.MarcID', $ids)
            ->select('a.SerialNo','b.ImageUrl', 'a.sold_price', 'a.rent_price', 'b.Profile','b.Price','b.Title')
            ->get();

        $res=false;
        foreach ($sel2 as $k => $v) {
            if (empty($v->ImageUrl) || empty($v->sold_price) || empty($v->rent_price) || empty($v->Profile) || empty($v->Price) || empty($v->Title)) {
                continue;
            }
            $res=DB::table('Items')->where('SerialNo',$v->SerialNo)->update(['LTStatus' => 2]);
        }

        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function pldcThirdCata()
    {
        $ids = $this->request->input('ids');
        $sel = DB::table('Items')
            ->wherein('SerialNo', $ids)
            ->where('LTStatus', 1);
        if (empty($sel->count())) {
            return Result::failure()->getResult();
        }

        $sel2 = DB::table('Items as a')
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->wherein('a.SerialNo', $ids)
            ->select('a.SerialNo','b.ImageUrl', 'a.sold_price', 'a.rent_price', 'b.Profile','b.Price','b.Title')
            ->get();

        $res=false;

        foreach ($sel2 as $k => $v) {
            if (empty($v->ImageUrl) || empty($v->sold_price) || empty($v->rent_price) || empty($v->Profile) || empty($v->Price) || empty($v->Title)) {
                continue;
            }
            $res=DB::table('Items')->where('SerialNo',$v->SerialNo)->update(['LTStatus' => 2]);
        }
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function plhkCollect()
    {
        $ids = $this->request->input('ids');
        $res = DB::table('Items as a')
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->leftjoin('ttindex7 as c', 'c.ID', '=', 'b.IID')
            ->wherein('c.ID', $ids)->update(['LTStatus' => 1]);
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function plhkSecCollect()
    {
        $ids = $this->request->input('ids');
        $res = DB::table('Items as a')
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->wherein('b.MarcID', $ids)
            ->update(['LTStatus' => 1]);
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function plhkThirdCollect()
    {
        $ids = $this->request->input('ids');
        //更改书籍状态
        $res = DB::table('Items')->wherein('SerialNo', $ids)->update(['LTStatus' => 1]);
        if (empty($res)) {
            return Result::failure()->setType(1)->getResult();
        }
        return Result::success()->getResult();
    }

    public function dcThirdCata($id)
    {
        $sel = DB::table('Items')
            ->where('SerialNo', $id)
            ->where('LTStatus', 1);
        if (empty($sel->count())) {
            return Result::failure()->getResult();
        }

        $sel2 = DB::table('Items as a')
            ->where('a.SerialNo', $id)
            ->leftjoin('circ_marc as b', 'b.MarcID', '=', 'a.MarcID')
            ->select('b.ImageUrl', 'a.sold_price', 'a.rent_price', 'b.Profile','b.Price','b.Title')
            ->first();

        if (empty($sel2->ImageUrl) || empty($sel2->sold_price) || empty($sel2->rent_price) || empty($sel2->Profile) || empty($sel2->Price) || empty($sel2->Title)) {
            return Result::failure()->setMsg('书名、封面图片、售价、定价、租金、简介不能为空！')->getResult();
        }

        $res = $sel->update(['LTStatus' => 2]);
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    /**
     * 待上架图书列表
     * czs
     */
    public function collect()
    {
        $keyWord = $this->request->input('keyword');
        $res = Book::getCollect($keyWord, $this->limit)->getData();
        $this->request->flash();
        return view('back/book/collect')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('count2', $res['count2'])
            ->with('titleType', 'collect');
    }

    /**
     * 二级典藏
     */
    public function secCollect($id)
    {
        $res = Book::getSecCollect($id, $this->limit)->getData();
        return view('back/book/secCollect')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('count2', $res['count2'])
            ->with('id', $id)
            ->with('titleType', 'collect');
    }

    /**
     * 三级典藏
     */
    public function thirdCollect($id)
    {
        $iid = DB::table('circ_marc as a')
            ->where('a.MarcID', $id)->value('a.IID');
        $res = Book::getThirdCollect($id, $this->limit)->getData();
        return view('back/book/thirdCollect')
            ->with('res', $res['list'])
            ->with('count', $res['count'])
            ->with('id', $id)->with('titleType', 'collect')->with('iid', $iid);
    }

    public function editSecCollect($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $pic = book::getPic($id)->getData();
            if (empty($input['pic_url_only']) && empty($pic->img)) {
                return Result::failure()->setMsg("图片不能为空");
            }
            //单图更新
            if ($pic->img != $input['pic_url_only']) {
                $input['ImageUrl'] = $input['pic_url_only'];
                unset($input['pic_url_only']);
            } else {
                unset($input['pic_url_only']);
            }

            $res = book::updateData($input, $id);
            return $res->getResult();
        } else {
            $res = DB::table('circ_marc as a')
                ->where('a.MarcID', $id)
                ->select('a.Title', 'a.ImageUrl', 'a.Price', 'a.IID', 'a.Profile')
                ->first();
            return view('back.book.editSecCollect')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'collect');
        }
    }

    public function editThirdCollect($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $res = book::updateThirdCata($input, $id);
            return $res->getResult();
        } else {
            $res = DB::table('Items as a')
                ->where('a.SerialNo', $id)
                ->select('a.sold_price', 'a.rent_price', 'a.MarcID')
                ->first();
            return view('back.book.editThirdCollect')
                ->with('res', $res)
                ->with('id', $id)->with('titleType', 'collect');
        }
    }

    public function xjThirdCollect($id)
    {
        //更改书籍状态
        $res = DB::table('Items')->where('SerialNo', $id)->update(['LTStatus' => 1]);
        if (empty($res)) {
            return Result::failure()->setType(1)->getResult();
        }
        return Result::success()->getResult();
    }


    public function sjThirdCollect($id)
    {
        if ($this->request->isMethod('post')) {
            $sid = $this->request->input('sid');
            $column = $this->request->input('column');
            DB::beginTransaction();
            $res = DB::table('Items as a')->where('a.SerialNo', $id)->update(['a.LTStatus' => 3]);
            if (empty($res)) {
                DB::rollback();
                return Result::failure()->setType(1)->getResult();
            }
            $rfid = DB::table('TagInfo as a')
                ->leftjoin('Items as c', 'c.BarCode', '=', 'a.Barcode')
                ->where('c.SerialNo', $id)->value('a.rUID');
            if (empty($rfid)) {
                DB::rollback();
                return Result::failure()->setType(2)->getResult();
            }
            $did = DB::table('shelves as a')->leftjoin('doors as b', 'b.sid', '=', 'a.id')
                ->where('a.id', $sid)
                ->where('b.column', $column)
                ->value('b.id');
            if (empty($did)) {
                DB::rollback();
                return Result::failure()->setType(3)->getResult();
            }
            $data['did'] = $did;
            $data['rfid'] = $rfid;
            $data['created_at'] = time();
            $data['status'] = 1;
            $in = DB::table('door_books')->insert($data);
            if (empty($in)) {
                DB::rollback();
                return Result::failure()->setType(4)->getResult();
            }
            DB::commit();
            return Result::success()->getResult();
        } else {
            $res = DB::table('Items as a')
                ->where('a.SerialNo', $id)
                ->select('a.MarcID')
                ->first();
            $shelf = DB::table('shelves')->where('type', 1)->select('id', 'name')->get();
            return view('back.book.sjThirdCollect')
                ->with('shelf', $shelf)->with('res', $res)
                ->with('id', $id)->with('titleType', 'collect');
        }
    }

    public function sjThirdCata($id)
    {
        $sel = DB::table('Items')
            ->where('SerialNo', $id)
            ->where('LTStatus', 2);
        if (empty($sel->count())) {
            return Result::failure()->getResult();
        }
        $res = $sel->update(['LTStatus' => 3]);
        if ($res) {
            return Result::success()->getResult();
        } else {
            return Result::failure()->getResult();
        }
    }

    public function page()
    {
        $page = $this->request->input('pa');
        session(['pa' => $page]);
        return Result::success()->getResult();
    }

    /**
     * 图书类型列表
     */
    public function bookType()
    {
        $res = DB::table("book_type")->get();
        return view('back/book/bookType')->with('res', $res);
    }

    /**
     * Show the form for creating a new resource.
     * 添加景区类型
     * czs
     * @return \Illuminate\Http\Response
     */
    public function createType()
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $res = DB::table('book_type')->insert($input);
            if ($res) {
                return Result::success()->setType(0)->getResult();
            }
        } else {
            return view('back/book/createType');
        }
    }

    /**
     * 二级联动
     * czs
     */
    public function pull1()
    {
        $pid = $this->request->get('pid');
        $res = Book::pull1($pid);
        return $res->getData();
    }

    /**
     * 二级联动
     * czs
     */
    public function pull()
    {
        $pid = $this->request->get('pid');
        $res = Book::pull($pid);
        return $res->getData();
    }

    /**
     * czs
     */
    public function pull3()
    {
        $pid = $this->request->get('pid');
        $res = DB::table('regions')->where('pid', $pid)->select('id', 'name')->get();
        return Result::success()->setData($res)->getData();
    }

    /**
     * 景区编辑保存
     * czs
     */
    public function edit1($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $pic = book::getOne($id)->getData();

            //单图更新
            if ($pic->img != $input['pic_url_only']) {
                $data['img'] = $input['pic_url_only'];
                $data['isbn'] = $input['isbn'];
                unset($input['isbn']);
                unset($input['pic_url_only']);
                book::updateImg($data);
            } else {
                unset($input['isbn']);
                unset($input['pic_url_only']);
            }

            $res = book::updateData($input, $id);
            return $res->getResult();
        } else {
            $bookType = DB::table("book_type")->select('id', 'book_type')->get();
            $res = DB::table('Items as a')
                ->leftJoin('circ_marc as b', 'a.MarcID', '=', 'b.MarcID')
                ->leftjoin('ttindex7 as c', 'c.MarcID', '=', 'a.MarcID')
                ->leftjoin('img as d', 'd.isbn', '=', 'c.Content')
                ->where('a.SerialNo', $id)
                ->select('b.sold_price', 'b.rent_price', 'd.img', 'b.Profile', 'a.SerialNo as id', 'b.ImageUrl',
                    'b.type', 'b.Pages', 'c.Content as isbn')
                ->first();
            return view('back.book.edit')->with('res', $res)->with('bookType', $bookType);
        }
    }

    public function editType($id)
    {
        if ($this->request->isMethod('post')) {
            $input = $this->request->all();
            $res = DB::table('book_type')->where('id', $id)->update($input);
            if ($res) {
                return Result::success()->setType(0)->getResult();
            }
        } else {
            $res = DB::table('book_type')->where('id', $id)->first();
            return view('back.book.editType')->with('res', $res);
        }
    }

    /**
     * Remove the specified resource from storage.
     * 删除
     * czs
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {
        $del = book::deleteLine($id);
        return $del->getResult();
    }

    public function deleteType($id)
    {
        $del = book::deleteType($id);
        return $del->getResult();
    }

    /**
     * 禁用、启用
     * czs
     */
    public function able($id, $able)
    {
        $res = Scenery::able($id, $able);
        return $res->getResult();
    }
}
